package com.efast.cafe.portal.controller.api;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.controller.AbstractController;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.vo.DataTableVo;
import com.efast.cafe.portal.bean.api.PortalApiObjectBean;
import com.efast.cafe.portal.bean.api.PortalApiObjectDto;
import com.efast.cafe.portal.bean.api.PortalApiObjectQueryBean;
import com.efast.cafe.portal.bean.common.EntityFieldInfoBean;
import com.efast.cafe.portal.bean.common.EntityInfoBean;
import com.efast.cafe.portal.entity.api.PortalApiField;
import com.efast.cafe.portal.remote.common.EntityInfoQueryService;
import com.efast.cafe.portal.service.api.IPortalApiObjectService;
import com.efast.cafe.util.StringUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

/**
 * <p>
 * Controller
 * </p>
 * <p>
 * Table: portal_api_object - 对象定义
 * </p>
 *
 * @since 2017-08-10 02:38:15
 */
@Controller
@RequestMapping("/frame_center/api")
public class PortalApiObjectController extends AbstractController {
	@Autowired
	private IPortalApiObjectService portalApiObjectService;
	@Autowired
	private EntityInfoQueryService entityInfoQueryService;

	//去重
	private List<PortalApiField> removeDuplicateFiled(List<PortalApiField> list){
		if(list!=null){
			Set<PortalApiField> set = new TreeSet<PortalApiField>((f1,f2) -> f1.getFieldName().compareToIgnoreCase(f2.getFieldName()));
			set.addAll(list);
			return new ArrayList<PortalApiField>(set);
		}
		return new ArrayList<PortalApiField>();
	}
	
	/**
	 * 新增Object
	 * 
	 * @Date : 2017年8月12日
	 * @param portalApiObjectBean
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/add")
	public @ResponseBody ResultBean insertApiObject(@RequestBody PortalApiObjectBean portalApiObjectBean, HttpServletRequest request) {
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			int oldFieldSize = portalApiObjectBean.getFieldList()!=null?portalApiObjectBean.getFieldList().size():0;
			if(removeDuplicateFiled(portalApiObjectBean.getFieldList()).size()!=oldFieldSize){
				throw new ServiceException("字段重复");
			}
			
			List<PortalApiField> oldFieldList = portalApiObjectBean.getFieldList()!=null?portalApiObjectBean.getFieldList():new ArrayList<>();
			if(StringUtil.isNotBlank(portalApiObjectBean.getInherit())){
				EntityInfoBean parentBean =	entityInfoQueryService.queryEntityInfo(portalApiObjectBean.getInherit());
				if(parentBean==null)
					throw new ServiceException("没有找到继承的实体");
				List<EntityFieldInfoBean> plist = parentBean.getAttrs();
				plist.forEach(b->{
					if(b.getField().getIsPk()!=null && b.getField().getIsPk().intValue()!=1){
					PortalApiField f = new PortalApiField();
					f.setFieldName(b.getField().getFieldName());
					oldFieldList.add(f);
					}});
				int checkSize = oldFieldList.size();
				if(removeDuplicateFiled(oldFieldList).size()!=checkSize){
					throw new ServiceException("和父实体的字段存在重复。");
				}
			}
			portalApiObjectService.insertApiObject(portalApiObjectBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}
		return result;
	}

	/**
	 * 修改object
	 * 
	 * @Date : 2017年8月12日
	 * @param portalApiObjectBean
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/update")
	public @ResponseBody ResultBean updateApiObject(@RequestBody PortalApiObjectBean portalApiObjectBean, HttpServletRequest request) {
		//RequestContext context = new RequestContext(request);
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			
			
			int oldFieldSize = portalApiObjectBean.getFieldList()!=null?portalApiObjectBean.getFieldList().size():0;
			if(removeDuplicateFiled(portalApiObjectBean.getFieldList()).size()!=oldFieldSize){
				throw new ServiceException("字段重复");
			}
			
			List<PortalApiField> oldFieldList = portalApiObjectBean.getFieldList()!=null?portalApiObjectBean.getFieldList():new ArrayList<>();
			if(StringUtil.isNotBlank(portalApiObjectBean.getInherit())){
				EntityInfoBean parentBean =	entityInfoQueryService.queryEntityInfo(portalApiObjectBean.getInherit());
				if(parentBean==null)
					throw new ServiceException("没有找到继承的实体");
				List<EntityFieldInfoBean> plist = parentBean.getAttrs();
				plist.forEach(b->{
					if(b.getField().getIsPk()!=null && b.getField().getIsPk().intValue()!=1){
					PortalApiField f = new PortalApiField();
					f.setFieldName(b.getField().getFieldName());
					oldFieldList.add(f);
					}});
				int checkSize = oldFieldList.size();
				if(removeDuplicateFiled(oldFieldList).size()!=checkSize){
					throw new ServiceException("和父实体的字段存在重复。");
				}
			}
			
			portalApiObjectService.updateApiObject(portalApiObjectBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}
		return result;
	}

	/**
	 * 删除object
	 * 
	 * @Date : 2017年8月12日
	 * @param portalApiObjectBean
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/delete")
	public @ResponseBody ResultBean deleteApiObject(@RequestBody PortalApiObjectBean portalApiObjectBean, HttpServletRequest request) {
		//RequestContext context = new RequestContext(request);
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			portalApiObjectService.deleteApiObject(portalApiObjectBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}
		return result;
	}

	/**
	 * 查询Object基本信息
	 * 
	 * @Date : 2017年8月14日
	 * @param portalApiObjectBean
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/detail")
	public @ResponseBody ResultBean queryObjByObjId(@RequestBody PortalApiObjectBean portalApiObjectBean, HttpServletRequest request) {
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			portalApiObjectBean = portalApiObjectService.queryObjByObjId(portalApiObjectBean);
			result.setObject(portalApiObjectBean);
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}
		return result;
	}

	/**
	 * 对象发布
	 * 
	 * @Date : 2017年8月15日
	 * @param portalApiObjectBean
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/publish")
	public @ResponseBody ResultBean publishApiObject(@RequestBody PortalApiObjectBean portalApiObjectBean, HttpServletRequest request) {
		//RequestContext context = new RequestContext(request);
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			portalApiObjectService.publishApiObject(portalApiObjectBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}
		return result;
	}

	/**
	 * 对象升级
	 * 
	 * @Date : 2017年8月23日
	 * @param portalApiObjectBean
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/upgrade")
	public @ResponseBody ResultBean upgradeApiObject(@RequestBody PortalApiObjectBean portalApiObjectBean, HttpServletRequest request) {
		//RequestContext context = new RequestContext(request);
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			portalApiObjectService.upgradeApiObject(portalApiObjectBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}
		return result;
	}

	/**
	 * 通过projectId查询所有的object
	 * 
	 * @Date : 2017年8月17日
	 * @param projectId
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/queryAllObjectByProId")
	public @ResponseBody DataTableVo<PortalApiObjectDto> queryAllObjectByProId(@RequestBody PortalApiObjectDto portalApiObjectDto, HttpServletRequest request) {
		return outPageJSONArray_bootstrapDatatable(portalApiObjectService.queryAllObjectByProId(portalApiObjectDto));
	}

	/**
	 * 通过moduleId查询所有的最新的object信息
	 * 
	 * @Date : 2017年8月21日
	 * @param portalApiObjectDto
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/queryObjectByModuleId")
	public @ResponseBody DataTableVo<PortalApiObjectDto> queryObjectByModuleId(@RequestBody PortalApiObjectDto portalApiObjectDto, HttpServletRequest request) {
		return outPageJSONArray_bootstrapDatatable(portalApiObjectService.queryObjectByModuleId(portalApiObjectDto));
	}

	/**
	 * 通过object的uuid查询所有该模块下的object的版本
	 * 
	 * @Date : 2017年8月21日
	 * @param portalApiObjectDto
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/queryObjectByObjcetUUid")
	public @ResponseBody ResultBean queryObjectByObjcetUUid(@RequestBody PortalApiObjectDto portalApiObjectDto, HttpServletRequest request) {
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			result.setObject(portalApiObjectService.queryObjectByObjcetUUid(portalApiObjectDto));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}

		return result;
	}

	/**
	 * 校验object的系统标识符，在syetem下面唯一
	 * 
	 * @Date : 2017年9月8日
	 * @param portalApiObjectDto
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/objIndentifierCount")
	public @ResponseBody ResultBean objIndentifierCount(@RequestBody PortalApiObjectBean apiObjectBean, HttpServletRequest request) {
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			portalApiObjectService.objIndentifierCount(apiObjectBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}

		return result;
	}

	/**
	 * 查询所有对象
	 * 
	 * @Date : 2017年9月12日
	 * @param portalApiObjectDto
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/queryAllObjectList")
	public @ResponseBody DataTableVo<PortalApiObjectDto> queryAllObjectList(@RequestBody PortalApiObjectQueryBean apiObjectQueryBean, HttpServletRequest request) {
		return outPageJSONArray_bootstrapDatatable(portalApiObjectService.queryAllObjectList(apiObjectQueryBean));
	}

	/**
	 * 查询所有对象
	 * 
	 * @Date : 2017年9月12日
	 * @param portalApiObjectDto
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/queryAll")
	public @ResponseBody ResultBean queryAll(@RequestBody PortalApiObjectQueryBean apiObjectQueryBean, HttpServletRequest request) {

		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			result.setObject(outPageJSONArray_bootstrapDatatable(portalApiObjectService.queryAllObjectList(apiObjectQueryBean)));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}

		return result;
	}
	
	/**
	 * 通过systemId查询所有的最新的object信息
	 * 
	 * @Date : 2017年8月21日
	 * @param portalApiObjectDto
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/queryObjectBySystemId")
	public @ResponseBody DataTableVo<PortalApiObjectDto> queryObjectBySystemId(@RequestBody PortalApiObjectDto portalApiObjectDto, HttpServletRequest request) {
		return outPageJSONArray_bootstrapDatatable(portalApiObjectService.queryObjectBySystemId(portalApiObjectDto));
	}
	
	
	/**
	 * 修改object
	 * 
	 * @Date : 2017年8月12日
	 * @param portalApiObjectBean
	 * @param request
	 * @return
	 */
	@RequestMapping("/object/updateLayout")
	public @ResponseBody ResultBean updateApiObjectLayout(@RequestBody PortalApiObjectDto portalApiObjectBean, HttpServletRequest request) {
		//RequestContext context = new RequestContext(request);
		ResultBean result = new ResultBean();
		result.setSuccess(true);
		try {
			portalApiObjectService.updateApiObjectLayout(portalApiObjectBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setMessage(e.getMessage());
			} else {
				// result.setMessage(context.getMessage(ADD_FAILURE_TIP));
			}
		}
		return result;
	}
	
}